package org.demo.system.mapper.impl;

import lombok.SneakyThrows;
import org.demo.base.auth.domain.Permission;
import org.demo.system.mapper.PermissionMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import org.springframework.util.CollectionUtils;

import java.sql.ResultSet;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author tomdog
 */
// @Repository
public class PermissionMapperImpl implements PermissionMapper {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    /**
     * 根据roleKeys查询所有权限
     * @param roleKeys
     * @return
     */
    @Override
    public List<Permission> listByRoleKeys(Collection<String> roleKeys) {
        if(CollectionUtils.isEmpty(roleKeys)) {
            return Collections.emptyList();
        }
        // 先拼问号，然后拼为sql
        String collect = roleKeys.stream().map(e -> "?").collect(Collectors.joining(","));
        String sql = "select aa.id, aa.permission_key, aa.`desc`, bb.role_key " +
                "from t_sys_permission aa left join t_sys_role_permission bb on aa.permission_key=bb.permission_key " +
                "where bb.role_key in ("+collect+")";
        // 进行查询
        List<Permission> list = jdbcTemplate.query(sql, this::mapToBean, roleKeys.toArray());
        return list;
    }

    /**
     * 把结果集转为域对象
     * 对象关系映射
     * @param rs
     * @param rowNum
     * @return
     */
    @SneakyThrows
    private Permission mapToBean(ResultSet rs, int rowNum) {
        return Permission.builder()
                .id(rs.getLong("id"))
                .permissionKey(rs.getString("permission_key"))
                .desc(rs.getString("desc"))
                .roleKey(rs.getString("role_key"))
                .build();
    }
}
